package com.partner.action.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.HttpRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import Decoder.BASE64Decoder;

import com.partner.bean.login.Userinfo;
import com.partner.bean.sysbase.TSystemsetting;
import com.partner.frame.BaseAction;
import com.partner.frame.Result;
import com.partner.frame.common.CommonInstans;
import com.partner.frame.common.ConstantsMark;
import com.partner.frame.common.GetProPertiesUtil;
import com.partner.service.sysbase.SystemSettingService;

import org.springframework.web.multipart.MultipartFile;

@RestController
public class CommonAction extends BaseAction {

	
	@Autowired
	private SystemSettingService systemSettingService;

	// 保存文件的目录
		private static String PATH_FOLDER = "F:/dylan/nginx-root/cdn/image";
		// 存放临时文件的目录
		private static String TEMP_FOLDER = "F:/dylan/nginx-root/cdn/image";
	
	
	/**
	 * pc管理端用户上传图片
	 * 
	 * @throws JSONException
	 * 
	 */
	@PostMapping("/common/pcuploadImage2")
	public void uploadPic2(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {  
		  
		response.setContentType("text/html");     
        response.setCharacterEncoding("UTF-8");  
        String realDir = request.getSession().getServletContext().getRealPath("");  
        String contextpath = request.getContextPath();  
        String basePath = request.getScheme() + "://"  
        + request.getServerName() + ":" + request.getServerPort()  
        + contextpath + "/";  
  
        try {  
          
        String realPath =""; //realDir+"\\"+filePath;  
        //判断路径是否存在，不存在则创建  
        File dir = new File(realPath);  
        if(!dir.isDirectory())  
            dir.mkdir();  
  
        if(ServletFileUpload.isMultipartContent(request)){  
  
            DiskFileItemFactory dff = new DiskFileItemFactory();  
            dff.setRepository(dir);  
            dff.setSizeThreshold(1024000);  
            ServletFileUpload sfu = new ServletFileUpload(dff);  
            FileItemIterator fii = null;  
            fii = sfu.getItemIterator(request);  
            String title = "";   //图片标题  
            String url = "";    //图片地址  
            String fileName = "";  
            String state="SUCCESS";  
            String realFileName="";  
            while(fii.hasNext()){  
                FileItemStream fis = fii.next();  
  
                try{  
                    if(!fis.isFormField() && fis.getName().length()>0){  
                        fileName = fis.getName();  
                        Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$");  
                        Matcher matcher=reg.matcher(fileName);  
                        if(!matcher.find()) {  
                            state = "文件类型不允许！";  
                            break;  
                        }  
                        realFileName = new Date().getTime()+fileName.substring(fileName.lastIndexOf("."),fileName.length());  
                        url = realPath+"\\"+realFileName;  
  
                        BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流  
                        FileOutputStream a = new FileOutputStream(new File(url));  
                        BufferedOutputStream output = new BufferedOutputStream(a);  
                        Streams.copy(in, output, true);//开始把文件写到你指定的上传文件夹  
                    }else{  
                        String fname = fis.getFieldName();  
  
                        if(fname.indexOf("pictitle")!=-1){  
                            BufferedInputStream in = new BufferedInputStream(fis.openStream());  
                            byte c [] = new byte[10];  
                            int n = 0;  
                            while((n=in.read(c))!=-1){  
                                title = new String(c,0,n);  
                                break;  
                            }  
                        }  
                    }  
  
                }catch(Exception e){  
                    e.printStackTrace();  
                }  
            }  
            response.setStatus(200);  
            //String retxt ="{src:'"+basePath+filePath+"/"+realFileName+"',status:success}";  
            //response.getWriter().print(retxt);  
        }  
        }catch(Exception ee) {  
            ee.printStackTrace();  
        }  
          
    } 
    
	/**
	 * pc管理端用户上传图片
	 * 
	 * @throws JSONException
	 * 
	 */
	@PostMapping("/common/pcuploadImage1")
	public void uploadPic(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {  
		  
		request.setCharacterEncoding("utf-8"); // 设置编码
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		// 获得磁盘文件条目工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		String  TEMP_FOLDER = "uploadfiles";
		// 如果没以下两行设置的话，上传大的 文件 会占用 很多内存，
		// 设置暂时存放的 存储室 , 这个存储室，可以和 最终存储文件 的目录不同
		/**
		 * 原理 它是先存到 暂时存储室，然后在真正写到 对应目录的硬盘上， 按理来说 当上传一个文件时，其实是上传了两份，第一个是以 .tem
		 * 格式的 然后再将其真正写到 对应目录的硬盘上
		 */
		factory.setRepository(new File(TEMP_FOLDER));
		// 设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
		factory.setSizeThreshold(1024 * 1024);

		// 高水平的API文件上传处理
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		try {
			// 提交上来的信息都在这个list里面
			// 这意味着可以上传多个文件
			// 请自行组织代码
			List<FileItem> list = upload.parseRequest(request);
			// 获取上传的文件
			FileItem item = getUploadFileItem(list);
			// 获取文件名
			String filename = getUploadFileName(item);
			// 保存后的文件名
			String saveName = new Date().getTime() + filename.substring(filename.lastIndexOf("."));
			// 保存后图片的浏览器访问路径
			String picUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/upload/"+saveName;

			System.out.println("存放目录:" + PATH_FOLDER);
			System.out.println("文件名:" + filename);
			System.out.println("浏览器访问路径:" + picUrl);

			// 真正写到磁盘上
			item.write(new File(PATH_FOLDER, saveName)); // 第三方提供的
			
			PrintWriter writer = response.getWriter();
			
			writer.print("{");
			writer.print("msg:\"文件大小:"+item.getSize()+",文件名:"+filename+"\"");
			writer.print(",picUrl:\"" + picUrl + "\"");
			writer.print("}");
			
			writer.close();
		
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    } 
	
	private FileItem getUploadFileItem(List<FileItem> list) {
		for (FileItem fileItem : list) {
			if(!fileItem.isFormField()) {
				return fileItem;
			}
		}
		return null;
	}
	
	private String getUploadFileName(FileItem item) {
		// 获取路径名
		String value = item.getName();
		// 索引到最后一个反斜杠
		int start = value.lastIndexOf("/");
		// 截取 上传文件的 字符串名字，加1是 去掉反斜杠，
		String filename = value.substring(start + 1);
		
		return filename;
	}
	
	
	
	/**
	 * pc管理端用户上传图片
	 * 
	 * @throws JSONException
	 * 
	 */
	@PostMapping("/common/pcuploadImage")
	public Result uploadify(@RequestParam("Filedata")MultipartFile filedata,
            @RequestParam(required = false, defaultValue = "1")String thumbnail) throws Exception{
		Result rs = new Result();
        TSystemsetting systemSetting = systemSettingService.getSystemSetting(CommonInstans.SYSTEMSETTING_TAG);
        //图片保存目录路径
        String savePath = systemSetting.getImagepath();

       //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
        extMap.put("mobile", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,apk");

        //最大文件大小
        //long maxSize = 1000000;

        //检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
        	rs.setDesc(ConstantsMark.UPLOADPATH_NOEXSIT);
            return rs;
        }
        //检查目录写权限
        if (!uploadDir.canWrite()) {
        	rs.setDesc(ConstantsMark.UPLOADPATH_NOREADWRITERIGHT);
            return rs;
        }
        String dirName = "image";
        if (!extMap.containsKey(dirName)) {
        	rs.setDesc(ConstantsMark.UPLOADPATH_DIRNAMEERROR);
            return rs;
        }
        //创建文件夹
        savePath += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }

        String fileName = filedata.getOriginalFilename();
       
        //检查扩展名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
        	rs.setDesc("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
            return rs;
        }

        File uploadedFile3 = new File(savePath, fileName);
        filedata.transferTo(uploadedFile3);
           
        rs.setDesc(ConstantsMark.SUCCESS);
        rs.setStatus(ConstantsMark.SUCCESS);
        rs.setObject(fileName);
        return rs ;
	}
	
	
	/**
	 * 移动端用户上传图片
	 * 
	 * @throws JSONException
	 * 
	 */
	@PostMapping("/common/uploadImage")
	public Result uploadImage(HttpServletRequest request,HttpServletResponse respose) throws IOException,
			JSONException {
		Result rs = new Result();
		rs.setStatus(ConstantsMark.COMMON_ERROR);
		rs.setObject(ConstantsMark.COMMON_BLANK);

		StringBuffer buffer = new StringBuffer();
		request.setCharacterEncoding("UTF-8");
		//String line = "";
		//BufferedReader reader = request.getReader();
//		while ((line = reader.readLine()) != null) {
//			buffer.append(line);
//		}
		int isinput = 0 ;
		ServletInputStream reader = request.getInputStream();
		int line;
        while ((line = reader.read()) != -1)
        {
        	buffer.append(line);
        	++isinput;
        }
        if(isinput==0){
        	rs.setDesc(ConstantsMark.IMAGE_NULLINPUT);
        	return rs ; 
        }
		JSONObject object = new JSONObject(buffer.toString());
		String imagebase64 = object.getString("picture");
		String account = object.getString("account");
		//String session = object.getString("session");
		String templetno = object.getString("templetno");//上传模板背景图片时传入
		String usetype = object.getString("usetype");//(head：头像，back：名片背景)
		
		//Userinfo userinfo = userinfoService.userAll(account);

//		if (userinfo == null) {
//			rs.setStatus(ConstantsMark.COMMON_ERROR);
//			rs.setDesc(ConstantsMark.ACCOUNT_NOTEXSIT);
//			return rs;
//		}
//
//		if (!userinfo.getOnline().equals(CommonInstans.YES_TAG)) {
//			rs.setDesc(ConstantsMark.USER_ISNOTONLINE);
//			return rs;
//		}
//		if (!userinfo.getSession().equals(session)) {
//			rs.setStatus(ConstantsMark.SESSION_LOGINRROR);
//			rs.setDesc(ConstantsMark.USER_OTHERMOBILELOGINED);
//			return rs;
//		}
		
		String imagepath ="" ;
		String imagesavepath = GetProPertiesUtil.getProperties("system.properties","file.upload.path");
		if(usetype.equals("head")){
			imagepath = this.byte2imagehead("", imagebase64, account,imagesavepath);
		}else if(usetype.equals("back")){
			imagepath = this.byte2imageback(templetno, imagebase64, account,imagesavepath);
		}
		
		rs.setStatus(ConstantsMark.SUCCESS);
		rs.setObject(imagepath);
		return rs;
	}

	/**
	 * 保存头像图片并返回头像存储地址
	 * 
	 * @param data
	 * @param imagebytes
	 * @param account
	 * @throws IOException
	 */
	public String byte2imagehead(String usetype, String imagebytes, String account,String imagesavepath)
			throws IOException {
		//文件保存目录路径
		String savePath = imagesavepath + "image/headimage/";
		String showpath = "image/headimage/" + account + ".png";
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] data = decoder.decodeBuffer(imagebytes);
		if (data.length < 3 || imagebytes.equals("")) {
		} else {
			// 检查目录
			File saveDirFile = new File(savePath);
			if (!saveDirFile.isDirectory()) {
				saveDirFile.mkdirs();
			}
			FileImageOutputStream imageOutput = new FileImageOutputStream(
					new File(savePath + account + ".png"));
			imageOutput.write(data, 0, data.length);
			imageOutput.close();
		}
		Userinfo user = new Userinfo();
		user.setAccount(account);
		user.setHeadimg(showpath);
		//userinfoService.upDate(user);
		
		return showpath;

	}
	/**
	 * 保存模板背景图片并返回存储地址
	 * 
	 * @param data
	 * @param imagebytes
	 * @param account
	 * @throws IOException
	 */
	public String byte2imageback(String templetno, String imagebytes, String account,String imagesavepath)
			throws IOException {
		
		//文件保存目录路径
		String savePath = imagesavepath + "image/backimage/";
		String showpath = "image/backimage/" +account+ new Date().getTime() + ".png";
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] data = decoder.decodeBuffer(imagebytes);
		if (data.length < 3 || imagebytes.equals("")) {
		} else {
			// 检查目录
			File saveDirFile = new File(savePath);
			if (!saveDirFile.isDirectory()) {
				saveDirFile.mkdirs();
			}
			FileImageOutputStream imageOutput = new FileImageOutputStream(
					new File(savePath +account+ new Date().getTime() + ".png"));
			imageOutput.write(data, 0, data.length);
			imageOutput.close();
		}
		//CardTempletPro ctp = new CardTempletPro();
//		ctp.setTempletno(templetno);
//		ctp.setProkey("back");
//		ctp.setProvalue(showpath);
//		ctp.setCreatetime(new Date());
//		cardTempletProService.updateByPrimaryKeySelective(ctp);

		return showpath;

	}
}
